/**
 * handle controller device register request.
 */
var cmdCodes = require("../CmdCode/cmdCode.js");
var proto = require("../Proto/proto.js");
var gatewayTable = require("../Redis/gatewayTable.js");
var redis = require("../Redis/redis.js");
var controllerTable = require("../Redis/controllerTable.js");

function gettime() {
	"use strict";
	var d = new Date();
	return d.toUTCString();
}

function registerHandler(cmd, c) {
	"use strict";
	
	var controllerId = cmd.devId;
	var creg = proto.parse(cmd.body, "CSControllerReg");
	var gwId = c.devId;
	creg.gwId = gwId;
	creg.devId = controllerId;
	console.error("controller register ok, id:" + controllerId + " details:");
	console.error(creg);
	
	var context = {};
	redis.setClient(context);
	
	context.beginMulti();
	gatewayTable.addController(context, gwId, controllerId, function(err) {
		if (err) {
			console.error("add controller failed:" + err);
		}
		
	});
	
	controllerTable.add(context, creg, function(err) {
		if (err) {
			console.error("add controller failed:" + err);
		}
	});
	context.endMulti(function(err) {
		if (err) {
			console.error("add controller failed:" + err);
		}
		
		c.sendCommand(cmd, {result:1}, "SCControllerRegReply");
	});
}

registerHandler.cmdCode = cmdCodes.CMD_CONTROLLER_REGISTER;
module.exports = registerHandler;
